package com.blahti.example.drag2;


import java.util.Calendar;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;
import com.icons.draw.view.*;


import data.Coordinate;
import data.ParkingDB;
import data.ParkingSpotsList;
public class DrawIcons extends MapActivity implements LocationListener{
	final int SUB_MENU_1 = 13;
	final int SUB_MENU_2 = 14;
	final int SUB_MENU_3 = 15;
	final int SUB_MENU_4 = 16;
	private MapLocationOverlay overlay;///
	private List<MapLocation> mapLocations;///
	public static MapView mapView;////
	MapController mapController;
	static final int EXIT_DIALOG=1;
	LocationManager lm;
	ParkingDB parking_db;
	static final int INTERVAL=60*1000;//every 0.5 minute
	private PendingIntent pendingIntent;
	int counter=0;
	ParkingSpotsList parkingResult;
	String street;
	String side;
	int j=0;

	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);
		parking_db=ParkingDB.getInstance();
		setContentView(R.layout.map);
		//check if working with gps or not
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
		if(sharedPrefs.getBoolean("USE_GPS", false)==true)
		{
			Log.d("DrawIcons","gps is true");
			parking_db.user_gps=true;
		}
		else
		{
			Log.d("DrawIcons","gps is false");
			parking_db.user_gps=false;
		}
			
		// mapView = (MapView) findViewById(R.id.mapview);
		ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);

		LocationViewers.mapView.getController().setZoom(21);
		// mapView.getMaxZoomLevel();
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
		//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {       
				LocationViewers.mapView.getController().zoomIn();      
			}
		});
		zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LocationViewers.mapView.getController().zoomOut();
			}
		});
		parking_db=ParkingDB.getInstance();

	}
	

	
	public void onStart(){
		super.onStart();
		Intent myIntent = new Intent(DrawIcons.this, RefreshService.class);
		pendingIntent = PendingIntent.getService(DrawIcons.this, 0, myIntent, 0);

		AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		calendar.add(Calendar.SECOND, 10);
		//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

		//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), INTERVAL, pendingIntent);
		//Toast.makeText(DrawIcons.this, "Start Service", Toast.LENGTH_LONG).show();
	}

	protected void onStop(){
		Log.d("onStop", "Main");
		super.onStop();
		AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
		stopService(new Intent(DrawIcons.this,RefreshService.class));
	}
	public void onDestroy(){
		super.onDestroy();
		AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
		stopService(new Intent(DrawIcons.this,RefreshService.class));
	}

	
	public boolean onCreateOptionsMenu(Menu menu) { 
		super.onCreateOptionsMenu(menu); 
		MenuInflater inflater = getMenuInflater(); 
		inflater.inflate(R.menu.menu, menu); 
		return true;

	}
	public boolean onOptionsItemSelected(MenuItem item) { 
		switch (item.getItemId()) { 
		case R.id.item11: 
			//ParkingDB parking_db=ParkingDB.getInstance();
			if(parking_db.myParking==true)
			{
				double lat=parking_db.mySpotLat;
				double longi=parking_db.mySpotLong;
				GeoPoint p=new GeoPoint((int)(lat*1E6),(int)(longi*1E6));
				LocationViewers.mapView.getController().animateTo(p);

				
			}
			else
				Toast.makeText (getApplicationContext(), "Your parking was not saved", Toast.LENGTH_LONG).show ();

			Log.d("Class4","menu item 11 selected");

			return true; 
		case R.id.item12: 
			Coordinate userLoc;
			if((parking_db.gps==true)&&(parking_db.userStreet!=null)&&(parking_db.user_gps==true))
				street=parking_db.userStreet;
			else
			{
				parking_db.userStreet="HaKovshim";
				street="HaKovshim";//street="Daniel";	//change to parking_db.userStreet	
			}
			if((parking_db.curLoc!=null)&&(parking_db.gps)&&(parking_db.user_gps==true))
			    userLoc=new Coordinate(parking_db.curLoc.longitude,parking_db.curLoc.latitude);
			else
				userLoc=new Coordinate(parking_db.noGpsLoc.longitude,parking_db.noGpsLoc.latitude);				

			side="A";
			boolean findStreetOnDB=false;
			if((parking_db.parkingVector!=null)&&(parking_db.serverOn))
			{
				for( j=0;j<parking_db.parkingVector.size();j++)
				{			        	
					if((parking_db.parkingVector.get(j).list.get(0).street.equals(street))&&(parking_db.parkingVector.get(j).list.get(0).side.equals(side)))
					{
						parkingResult=parking_db.parkingVector.elementAt(j);
						parking_db.listIndex_A=j;
						findStreetOnDB=true;
						break;
					}			        	
				}
				if(findStreetOnDB)
				findNearestParkingSpots(userLoc);
				
				findStreetOnDB=false;
				side="B";
				for( j=0;j<parking_db.parkingVector.size();j++)
				{			        	
					if((parking_db.parkingVector.get(j).list.get(0).street.equals(street))&&(parking_db.parkingVector.get(j).list.get(0).side.equals(side)))
					{
						parkingResult=parking_db.parkingVector.elementAt(j);
						parking_db.listIndex_B=j;
						findStreetOnDB=true;
						break;
					}			        	
				}
				if(findStreetOnDB)
				findNearestParkingSpots(userLoc);
			}   
			Intent intent = new Intent(LocationViewers.mapView.getContext(), DragActivityV2.class);
			
			intent.putExtra("listIndex_A", parking_db.listIndex_A);
			intent.putExtra("listIndex_B", parking_db.listIndex_B);
			
			intent.putExtra("A0",parking_db.IndexArray_A[0]);
			intent.putExtra("A1",parking_db.IndexArray_A[1]);
			intent.putExtra("A2",parking_db.IndexArray_A[2]);
			intent.putExtra("A3",parking_db.IndexArray_A[3]);
			intent.putExtra("A4",parking_db.IndexArray_A[4]);
			
			intent.putExtra("B0",parking_db.IndexArray_B[0]);
			intent.putExtra("B1",parking_db.IndexArray_B[1]);
			intent.putExtra("B2",parking_db.IndexArray_B[2]);
			intent.putExtra("B3",parking_db.IndexArray_B[3]);
			intent.putExtra("B4",parking_db.IndexArray_B[4]);
			
			LocationViewers.mapView.getContext().startActivity(intent);

			Log.d("Class4","menu item 12 selected");
			return true; 
		case R.id.item13: 
			Log.d("Class4","menu item 13 selected");
			Intent intent3 = new Intent(this, viewProfile.class); 
			startActivity(intent3);
			return true; 
		case R.id.item14: 
			Log.d("Class4","s menu item from s menue 3 selected");
			Intent intent2 = new Intent(this, ShowSettings.class); 
			startActivity(intent2);
			return true;
		case R.id.item15: 

			Log.d("Class4","menu item 15 selected");
			showDialog(EXIT_DIALOG);
			return true;


		}
		return super.onOptionsItemSelected(item); 
	}
	protected Dialog onCreateDialog(int id){
		Dialog dialog=null;
		switch(id){
		case EXIT_DIALOG:return createExitDialog();
		default: dialog=null;
		}
		return dialog;
	}
	private Dialog createExitDialog(){
		final Activity localActivity=this;
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to leave?")
		.setCancelable(false)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int id) {
				{
					SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
					SharedPreferences.Editor ed=ref.edit();
					ed.putString("exit", "true");
					ed.commit();
					localActivity.finish();
				}


			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});
		AlertDialog alert=builder.create();
		return alert;


	}


	/**
	 * Must let Google know that a route will not be displayed
	 */
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

		if ((location != null)&&(parking_db.gps)&&(parking_db.user_gps)) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			/*
			 String msg= "New network location: "
	                    + String.format("%9.6f", lat) + ", "
	                    + String.format("%9.6f", lng) + "\n";
	         Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
			 */
			
			if(parking_db.curLoc!=null)
			{
				parking_db.preLoc=new MapLocation("i am here",parking_db.curLoc.latitude,parking_db.curLoc.longitude);
			}	
			parking_db.curLoc=new MapLocation("i am here",lat,lng);
			Point cur = new Point();
			LocationViewers.mapView.getProjection().toPixels(parking_db.curLoc.getPoint(), cur);
		/*
			String msg= "New network location: "
					+ String.format("%d", cur.x) + ", "
					+ String.format("%d", cur.y) + "\n";
					*/
			//Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
			//LocationViewers.mapView.getController().setCenter(parking_db.curLoc.getPoint());
	
			if((parking_db.gps)&&(parking_db.user_gps))
			{
				LocationViewers.mapView.postInvalidate();
				handleReverseGeocodeClick();
				// msg= "draw"+"\n";
				//Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
			}
		}

	}

private void handleReverseGeocodeClick()
{
	if (parking_db.curLoc != null)
	{
		// Kickoff an asynchronous task to fire the reverse geocoding
		// request off to google
		ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
		task.applicationContext = this;
		task.execute();

	}
}


@Override
public void onProviderDisabled(String provider) {
	// TODO Auto-generated method stub
	String message = "GPS Disabled ";
	parking_db.gps=false;
//	Toast.makeText (getApplicationContext(), message, Toast.LENGTH_LONG).show ();
	//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);


}
@Override
public void onProviderEnabled(String provider) {
	// TODO Auto-generated method stub
	String message = "GPS Enabled ";
	parking_db.gps=true;
	//Toast.makeText (getApplicationContext(), message, Toast.LENGTH_LONG).show ();
	//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);


}



/* find nearest parking spot to user's location*/
private int findNearestParkingSpots(Coordinate userLoc)
{
	int nearestPS_I=0;
	int topNeighbor1_I=-1;
	int topNeighbor2_I=-1;
	int topNeighbor3_I=-1;
	int topNeighbor4_I=-1;
	int bottomNeighbor1_I = -1;
	int bottomNeighbor2_I=-1;
	int bottomNeighbor3_I=-1;
	int bottomNeighbor4_I=-1;
	int top=0;
	int bottom=0;

	side=parkingResult.list.get(nearestPS_I).side;



	for(int i=1;i<parkingResult.list.size();i++)
	{
		if(userLoc.distanceKM(parkingResult.list.get(nearestPS_I).parkingCordinate_B)+userLoc.distanceKM(parkingResult.list.get(nearestPS_I).parkingCordinate_A)>userLoc.distanceKM(parkingResult.list.get(i).parkingCordinate_B)+userLoc.distanceKM(parkingResult.list.get(i).parkingCordinate_A))
		{
			//nearestPS=parkingResult.list.get(i);
			nearestPS_I=i;
		}
	}

	/* find neighbor from top to nearestPS_SideA*/
	for(int i=1;i<parkingResult.list.size();i++)

	{

		if(parkingResult.list.get(i).parkingCordinate_A.equale(parkingResult.list.get(nearestPS_I).parkingCordinate_B))
		{
			topNeighbor1_I=i;
			top++;
			break;
		}
	}

	/* find neighbor from top to topNeighbor1*/
	if(topNeighbor1_I!=-1)
	{
		for(int i=1;i<parkingResult.list.size();i++)
		{
			if(parkingResult.list.get(i).parkingCordinate_A.equale(parkingResult.list.get(topNeighbor1_I).parkingCordinate_B))
			{
				topNeighbor2_I=i;
				top++;
				break;
			}
		}
	}

	/* find neighbor from bottom to nearestPS_SideA*/
	for(int i=1;i<parkingResult.list.size();i++)
	{

		//Log.d("other",Double.toString(parkingResult.list.get(i).parkingCordinate_A.latitude)+" "+Double.toString(parkingResult.list.get(i).parkingCordinate_A.longitude));

		if(parkingResult.list.get(i).parkingCordinate_B.equale(parkingResult.list.get(nearestPS_I).parkingCordinate_A))
		{
			bottomNeighbor1_I=i;
			bottom++;
			break;
		}
	}


	/* find neighbor from bottom to bottomNeighbor1*/
	if(bottomNeighbor1_I!=-1)
	{
		for(int i=1;i<parkingResult.list.size();i++)
		{
			if(parkingResult.list.get(i).parkingCordinate_B.equale(parkingResult.list.get(bottomNeighbor1_I).parkingCordinate_A))
			{
				bottomNeighbor2_I=i;
				bottom++;
				break;
			}
		}
	}


	if((bottom==2)&&(top==2))
	{
		if(side.equals("A"))
		{
			parking_db.IndexArray_A[0]=topNeighbor2_I;
			parking_db.IndexArray_A[1]=topNeighbor1_I;
			parking_db.IndexArray_A[2]=nearestPS_I;
			parking_db.IndexArray_A[3]=bottomNeighbor1_I;
			parking_db.IndexArray_A[4]=bottomNeighbor2_I;
		}
		else
		{
			parking_db.IndexArray_B[0]=topNeighbor2_I;
			parking_db.IndexArray_B[1]=topNeighbor1_I;
			parking_db.IndexArray_B[2]=nearestPS_I;
			parking_db.IndexArray_B[3]=bottomNeighbor1_I;
			parking_db.IndexArray_B[4]=bottomNeighbor2_I;
		}
		return 0;
	}
	else
		if((bottom<2)&&(top==2))
		{
			for(int i=1;i<parkingResult.list.size();i++)
			{
				if(parkingResult.list.get(i).parkingCordinate_A.equale(parkingResult.list.get(topNeighbor2_I).parkingCordinate_B))
				{
					topNeighbor3_I=i;
					top++;
					break;
				}
			}
			if((top==3)&&(bottom==0))
			{
				for(int i=1;i<parkingResult.list.size();i++)
				{
					if(parkingResult.list.get(i).parkingCordinate_A.equale(parkingResult.list.get(topNeighbor3_I).parkingCordinate_B))
					{
						topNeighbor4_I=i;
						top++;
						break;
					}
				}
			}
			if(top==4)
			{
				if(side.equals("A"))
				{
					parking_db.IndexArray_A[0]=topNeighbor4_I;
					parking_db.IndexArray_A[1]=topNeighbor3_I;
					parking_db.IndexArray_A[2]=topNeighbor2_I;
					parking_db.IndexArray_A[3]=topNeighbor1_I;
					parking_db.IndexArray_A[4]=nearestPS_I;
				}
				else
				{
					parking_db.IndexArray_B[0]=topNeighbor4_I;
					parking_db.IndexArray_B[1]=topNeighbor3_I;
					parking_db.IndexArray_B[2]=topNeighbor2_I;
					parking_db.IndexArray_B[3]=topNeighbor1_I;
					parking_db.IndexArray_B[4]=nearestPS_I;
				}

			}
			else if(top==3)
			{
				if(side.equals("A"))
				{
					parking_db.IndexArray_A[0]=topNeighbor3_I;
					parking_db.IndexArray_A[1]=topNeighbor2_I;
					parking_db.IndexArray_A[2]=topNeighbor1_I;
					parking_db.IndexArray_A[3]=nearestPS_I;
					parking_db.IndexArray_A[4]=bottomNeighbor1_I;
				}
				else
				{
					parking_db.IndexArray_B[0]=topNeighbor3_I;
					parking_db.IndexArray_B[1]=topNeighbor2_I;
					parking_db.IndexArray_B[2]=topNeighbor1_I;
					parking_db.IndexArray_B[3]=nearestPS_I;
					parking_db.IndexArray_B[4]=bottomNeighbor1_I;
				}

			}

			return 0;

		}
		else
			if((bottom==2)&&(top<2))
			{
				for(int i=1;i<parkingResult.list.size();i++)
				{
					if(parkingResult.list.get(i).parkingCordinate_B.equale(parkingResult.list.get(bottomNeighbor2_I).parkingCordinate_A))
					{
						bottomNeighbor3_I=i;
						bottom++;
						break;
					}
				}

				if((bottom==3)&&(top==0))
				{
					for(int i=1;i<parkingResult.list.size();i++)
					{
						if(parkingResult.list.get(i).parkingCordinate_B.equale(parkingResult.list.get(bottomNeighbor3_I).parkingCordinate_A))
						{
							bottomNeighbor4_I=i;
							bottom++;
							break;
						}
					}
				}

				if(bottom==4)
				{
					if(side.equals("A"))
					{
						parking_db.IndexArray_A[0]=nearestPS_I;
						parking_db.IndexArray_A[1]=bottomNeighbor1_I;
						parking_db.IndexArray_A[2]=bottomNeighbor2_I;
						parking_db.IndexArray_A[3]=bottomNeighbor3_I;
						parking_db.IndexArray_A[4]=bottomNeighbor4_I;
					}
					else
					{
						parking_db.IndexArray_B[0]=nearestPS_I;
						parking_db.IndexArray_B[1]=bottomNeighbor1_I;
						parking_db.IndexArray_B[2]=bottomNeighbor2_I;
						parking_db.IndexArray_B[3]=bottomNeighbor3_I;
						parking_db.IndexArray_B[4]=bottomNeighbor4_I;
					}

				}
				else if(bottom==3)
				{
					if(side.equals("A"))
					{
						parking_db.IndexArray_A[0]=topNeighbor1_I;
						parking_db.IndexArray_A[1]=nearestPS_I;
						parking_db.IndexArray_A[2]=bottomNeighbor1_I;
						parking_db.IndexArray_A[3]=bottomNeighbor2_I;
						parking_db.IndexArray_A[4]=bottomNeighbor3_I;
					}
					else
					{
						parking_db.IndexArray_B[0]=topNeighbor1_I;
						parking_db.IndexArray_B[1]=nearestPS_I;
						parking_db.IndexArray_B[2]=bottomNeighbor1_I;
						parking_db.IndexArray_B[3]=bottomNeighbor2_I;
						parking_db.IndexArray_B[4]=bottomNeighbor3_I;
					}

				}

				return 0;
			}

	return -1;



}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
	// TODO Auto-generated method stub
    switch (status) {
    case LocationProvider.AVAILABLE:
    	 parking_db.gps=true;
    	 break;
    case LocationProvider.OUT_OF_SERVICE:
    	 parking_db.gps=false;
         break;
    case LocationProvider.TEMPORARILY_UNAVAILABLE:
    	 parking_db.gps=false;

        break;
    }

}
  @Override
    protected void onResume() {
        super.onResume();
        Log.d("mor","onResume");
        LocationViewers.mapView.postInvalidate();
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, this);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        lm.removeUpdates(this);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
		stopService(new Intent(DrawIcons.this,RefreshService.class));

    }

}

